//
//  PostImgsView.m
//  sensen_ios
//
//  Created by pro on 16/3/1.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "PostImgsView.h"

#import "BigImageViewController.h"

#define KMarginWidth 10

@implementation PostImgsView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    
    return self;
}

- (void)setImgAry:(NSArray *)imgAry {
    
    if (self.subviews) {
        for (UIView *view in self.subviews) {
            [view removeFromSuperview];
        }
    }
    // [:f002}
    
    if (_imgAry != imgAry) {
        _imgAry = imgAry;
    }
    if (_imgAry.count == 0 || _imgAry == nil) {
    }
    else {
        
        // 创建图片视图
        CGFloat x, y, width, height;
        width = (SCREEN_WIDTH - 4 * KMarginWidth) / 3;
        height = width;
        for (int i = 0; i < _imgAry.count; i ++) {
            y = KMarginWidth + i / 3 * (height + KMarginWidth);
            x = KMarginWidth + i % 3 * (width + KMarginWidth);

            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
            imgView.userInteractionEnabled = YES;
            imgView.tag = 100 + i;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_pushToBigImgViewVC:)];
            [imgView addGestureRecognizer:tap];
            
            // 大图
            [self addSubview:imgView];

            // 加载网络图片
            [imgView setImageURLStr:_imgAry[i] placeholder:[UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:1]]];
            __weak UIImageView *w_imgView = imgView; // 防止循环调用
            [imgView setImageWithURL:[NSURL URLWithString:_imgAry[i]] placeholderImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:1]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                __strong UIImageView *s_imgView = w_imgView;
                if (image == nil) {
                    s_imgView.image = [UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:1]];
                } else {
                    // 设置为正方形的图片
                    s_imgView.image = [image getCenterImage];
                }
            }];
            
        }

    }
    
}


- (void)_pushToBigImgViewVC:(UITapGestureRecognizer *)tap {
    
    BigImageViewController *vc = [[BigImageViewController alloc] init];
    vc.imageData = self.imgAry;
    NSInteger index = tap.view.tag - 100;
    vc.indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    [self.viewController presentViewController:vc animated:YES completion:nil];
}

@end
